//  获取 res.data.records
import { expect } from '@playwright/test';

export const getRecordDataFromRes = async (res) => {
  return res.data.records;
};

//  获取 res.data.data 之类的数据
export const getDataFromRes = async (res) => {
  return res.data;
};

//获取搜索数据
export const searchGetData = async (api, page) => {
  const response = await page.waitForResponse((response) => response.url().includes(api) && response.status() === 200);
  const res = await response.json();
  const data = await getRecordDataFromRes(res);
  return data;
};

export const searchExcept = async (api, page, key, params, type) => {
  const searchCodeData = await searchGetData(api, page);
  if (searchCodeData.length > 0) {
    // 有数据
    searchCodeData.forEach((item) => {
      const itemValue = item[key];
      console.log(itemValue, params, type);
      // 根据不同类型进行验证
      if (type === 'datetimerange') {
        // 提取日期并比较
        const itemDate = itemValue.split(' ')[0]; // 获取 item 中的日期部分
        const paramsDate = params.split(' ')[0]; // 获取 params 中的日期部分
        expect(itemDate).toEqual(paramsDate); // 验证日期一致性
      } else {
        expect(itemValue).toBe(params);
      }
    });
  } else {
    expect(Array.isArray(searchCodeData)).toBeTruthy();
  }
};

export const searchEqualExcept = async (api, page, key, params) => {
  const searchCodeData = await searchGetData(api, page);
  if (searchCodeData.length > 0) {
    // 有数据
    searchCodeData.forEach((item) => {
      expect(item[key]).toEqual(params);
    });
  } else {
    expect(Array.isArray(searchCodeData)).toBeTruthy();
  }
};

export const generateRandomString = (len) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < len; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
